<script setup>
import { onMounted, ref, computed } from 'vue';
import ArticlesList from '../Article/ArticlesList.vue';
import PostList from '../Post/PostList.vue';
import NewPostSection from '../Post/NewPostSection.vue';
import HotTopics from './HotTopics.vue';
import { postService } from "@/services/PostService.js";
import ArticleModel from '../Article/ArticleModel.vue';
import { ElMessage, ElCard, ElRadioGroup, ElRadioButton } from 'element-plus';
import { userManager } from '@/utils/user';
const posts = ref([]);
const articles = ref([]);
const selectedArticle = ref(null);
const currentFilter = ref('recommend');

const fetchArticles = async () => {
  try {
    const userId = userManager.getUserId();
    const response = await postService.getAllArticles(userId);
    articles.value = response;
  } catch (error) {
    console.error("获取文章列表失败:", error);
  }
};

const refreshArticles = async () => {
  await fetchArticles();
};

const fetchPosts = async () => {
  try {
    const userId = userManager.getUserId();
    const response = await postService.getAllPosts(userId);
    posts.value = response;
    console.log('检查帖子数据和ID:', posts.value.map(p => p.id));
    console.log("帖子列表已更新:", posts.value);
  } catch (error) {
    console.error("获取帖子列表失败:", error);
    ElMessage({
      message: '获取帖子列表失败，请稍后重试！',
      type: 'error',
    });
  }
};
onMounted(()=>{
  refreshPosts();
})
const refreshPosts =  () => {
  fetchPosts();
  fetchArticles();
}
const filteredPosts = computed(() => {
  if (currentFilter.value === 'recommend') {
    return posts.value;
  }
  if(currentFilter.value === 'article') {
    return articles.value;
  }
  return posts.value.filter(post => post.filtertype === currentFilter.value);
});
const toggleLike = async(postId) => {
  const post = posts.value.find(p => p.id === postId);
  if (post) {
    const userId=userManager.getUserId();
    const isCurrentUserLiked = await postService.getLiked(postId,userId);
    post.liked = (isCurrentUserLiked === true ? false : true);
    post.likes += (isCurrentUserLiked === true ? -1 : +1);
  }
  try {
    const userId=userManager.getUserId();
    await postService.updatePostLikes(postId,userId);
    console.log("点赞状态修改成功！");
  } catch (error) {
    console.error("点赞操作失败:", error);
    ElMessage({
      message: '点赞操作失败，请稍后重试',
      type: 'error',
    });
  }
};
const handleArticleLike = async(articleId) => {
  const article = articles.value.find(a => a.id === articleId);
  if (article) {
    const userId=userManager.getUserId();
    const isCurrentUserLiked = await postService.getLiked(articleId,userId);
    console.log(isCurrentUserLiked);
    article.liked = (isCurrentUserLiked === true ? false : true);
    article.likes += (isCurrentUserLiked === true ? -1 : +1);
  }
  try {
    const userId=userManager.getUserId();
    await postService.updateArticleLikes(articleId,userId);
    console.log("点赞状态修改成功！");
  } catch (error) {
    console.error("点赞操作失败:", error);
    ElMessage({
      message: '点赞操作失败，请稍后重试',
      type: 'error',
    });
  }
};
const openArticleModel = (article) => {
  selectedArticle.value = article;
};
const closeArticleModel = () => {
  selectedArticle.value = null;
};
</script>

<template>
  <div class="forum-page">
    <div class="main-content">
      <div class="left-section">
        <NewPostSection @submitPost="refreshPosts" />

        <el-card shadow="never" class="post-filter-card">
          <el-radio-group v-model="currentFilter" size="small">
            <el-radio-button label="follow">关注</el-radio-button>
            <el-radio-button label="recommend">推荐</el-radio-button>
            <el-radio-button label="circle">圈子</el-radio-button>
            <el-radio-button label="salary">薪资爆料</el-radio-button>
            <el-radio-button label="offer">选offer</el-radio-button>
            <el-radio-button label="interview">面经</el-radio-button>
            <el-radio-button label="company">聊公司</el-radio-button>
            <el-radio-button label="article">文章</el-radio-button>
          </el-radio-group>
        </el-card>

        <div v-if="currentFilter === 'article'">
          <ArticlesList :articles="articles" @toggle-like="handleArticleLike" @view-article="openArticleModel" />
        </div>
        <div v-else>
          <PostList :posts="filteredPosts" @toggle-like="toggleLike" />
        </div>

        <ArticleModel
            v-if="selectedArticle"
            :article="selectedArticle"
            @close="closeArticleModel"
            @comment-added="refreshArticles"
        />
      </div>

      <aside class="right-sidebar">
        <el-card shadow="never" class="hot-topics-card">
          <HotTopics @view-article="openArticleModel" />
        </el-card>
      </aside>
    </div>
  </div>
</template>

<style scoped>
.forum-page {
  background-color: #f7f8fa;
  padding: 24px;
  /* --- 关键改动开始 --- */
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  box-sizing: border-box; /* 确保 padding 不会影响 min-height 计算 */
  /* --- 关键改动结束 --- */
}
.main-content {
  display: flex;
  justify-content: center;
  gap: 24px;
  max-width: 1280px;
  margin: 0 auto;
  align-items: flex-start;
  width: 100%;
  /* --- 关键改动开始 --- */
  flex-grow: 1; /* 让主内容区填满剩余空间 */
  /* --- 关键改动结束 --- */
}
.left-section {
  flex: 2;
  min-width: 600px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}
.right-sidebar {
  flex: 1;
  min-width: 280px;
  max-width: 350px;
  position: sticky;
  top: 24px; /* 与页面padding一致 */
}
.post-filter-card, .hot-topics-card {
  border-radius: 12px;
  border: 1px solid #e0e0e0;
  background-color: #fff; /* 确保卡片是白色 */
}
.post-filter-card :deep(.el-card__body) {
  padding: 12px 16px;
}
.post-filter-card :deep(.el-radio-button__inner) {
  border-radius: 6px !important;
  border: none;
  background: none;
  box-shadow: none;
  font-weight: 500;
}
.post-filter-card :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
  background-color: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}
</style>